package x.java.tea;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class IteratorInjector extends ObjectInjector {
	private int idx;
	
	protected Iterator<? extends Object> it;
	
	public IteratorInjector() {
	}
	
	public IteratorInjector(Iterator<Object> it) {
		this.it = it;
	}
	
	public IteratorInjector(Collection<? extends Object> c) {
		if (c != null) {
			this.it = new ArrayList<Object>(c).iterator();
		}
	}

	public IteratorInjector(Object[] a) {
		if (a != null) {
			this.it = Arrays.asList(a).iterator();
		}
	}

	public void setIterator(Iterator<Object> it) {
		this.it = it;
	}
	
	public void setIterator(Collection<Object> c) {
		this.it = c.iterator();
	}

	@Override
	public void init(String id) {
		idx = -1;
		super.init(id);
	}
	
	@Override
	public int inject(byte[] b) throws IOException {
		while (hasNext()) {
			Object obj = next();
			setObject(obj);
			doInit("["+idx+"]");
			int c = doInject(b);
			if (c != -1) {
				return c;
			}
		}
		return -1;
	}
	
	protected boolean hasNext() {
		return (it != null && it.hasNext());
	}

	protected Object next() {
		idx++;
		return it.next();
	}

	protected void remove() {
		throw new UnsupportedOperationException();
	}
}
